package leetcode.binaryTree;

import utils.printer.BinaryTrees;
import datastructure.tree.BinarySearchTree;
import datastructure.tree.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @Description: https://leetcode.cn/problems/binary-tree-postorder-traversal/
 * 给你一棵二叉树的根节点 root ，返回其节点值的 后序遍历 。
 * @Author Ammar
 * @Create 2023/3/29 17:51
 */
public class _145_二叉树的后序遍历 {
    public static List<Integer> postorderTraversal1(TreeNode<Integer> root) {
        List<Integer> datas = new ArrayList<>();
        if (root == null) return datas;
        datas.addAll(postorderTraversal(root.left));
        datas.addAll(postorderTraversal(root.right));
        datas.add(root.val);
        return datas;
    }

    public static List<Integer> postorderTraversal(TreeNode<Integer> root) {
        List<Integer> datas = new ArrayList<>();
        if (root == null) return datas;
        Stack<TreeNode<Integer>> stack = new Stack<>();
        stack.push(root);
        TreeNode<Integer> prev = null;
        while (!stack.isEmpty()) {
            TreeNode<Integer> node = stack.peek();
            if (node.isLeaf() || (prev != null && prev.parent == node)) {
                prev = stack.pop();
                datas.add(prev.val);
            } else {
                if (node.right != null) stack.push(node.right);
                if (node.left != null) stack.push(node.left);
            }
        }
        return datas;
    }

    public static void main(String[] args) {
        Integer[] data = new Integer[]{
                7, 4, 9, 2, 5, 8 ,11, 3, 12, 1
        };
        BinarySearchTree<Integer> binarySearchTree = new BinarySearchTree<>();
        for (int i = 0; i < data.length; i++) {
            binarySearchTree.add(data[i]);
        }
        BinaryTrees.print(binarySearchTree);
        List<Integer> integers = postorderTraversal(binarySearchTree.getRoot());
        integers.forEach(System.out::println);
    }
}
